package com.life.controller;

import com.github.pagehelper.Page;
import com.life.constant.MessageConstant;
import com.life.pojo.dto.FileDTO;
import com.life.pojo.dto.FileQueryDTO;
import com.life.pojo.entity.File;
import com.life.pojo.vo.FileVO;
import com.life.result.PageResult;
import com.life.result.Result;
import com.life.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/admin/file")
@Api(tags = "文件接口")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public Result<FileVO> upload(MultipartFile file, String type) {
        try {
            FileVO fileVO = fileService.save(file, type);
            return Result.success(fileVO);
        } catch (Exception e) {
            log.error("文件上传失败：{}", e.toString());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

    @GetMapping
    @ApiOperation("获取文件列表")
    public Result<PageResult> list(FileQueryDTO fileQueryDTO) {
        log.info("获取文件列表：{}", fileQueryDTO);
        Page<FileVO> page = fileService.list(fileQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return Result.success(pageResult);
    }

    @PutMapping
    @ApiOperation("更新文件")
    public Result<String> updateFile(@RequestBody FileDTO fileDTO) {
        log.info("更新文件：{}", fileDTO);
        File file = new File();
        BeanUtils.copyProperties(fileDTO, file);
        fileService.update(file);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除文件")
    public Result<String> delete(@PathVariable Long id) {
        log.info("删除文件：{}", id);
        fileService.delete(id);
        return Result.success();
    }
}
